package com.peanut.baby.mvp.profileedit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.peanut.baby.AppConfig;
import com.peanut.baby.InitManager;
import com.peanut.baby.R;
import com.peanut.baby.comm.BaseDialog;
import com.peanut.baby.http.HttpConfig;
import com.peanut.baby.model.AuthrizeInfo;
import com.peanut.baby.model.UStatus;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.model.User;
import com.peanut.baby.mvp.BaseMvpActivity;
import com.peanut.baby.mvp.subscribe.TagSubscribeActivity;
import com.peanut.baby.mvp.web.WebViewActivity;
import com.peanut.baby.util.AppUtil;
import com.peanut.baby.widget.citypicker.CityParseHelper;
import com.peanut.devlibrary.RequestResult;
import com.peanut.devlibrary.imageloader.ImageLoader;
import com.peanut.devlibrary.picker.ImageConfig;
import com.peanut.devlibrary.picker.PhotoPickerActivity;
import com.peanut.devlibrary.util.StringUtil;
import com.peanut.devlibrary.widget.TitleLayout;
import com.tencent.mars.xlog.Log;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * 个人信息编辑
 */
public class ProfileEditActivity extends BaseMvpActivity implements View.OnClickListener,
        TitleLayout.OnTitleClickListener, ProfileEditContract.View {
    private static final String TAG = ProfileEditActivity.class.getSimpleName();


    @BindView(R.id.title)
    TitleLayout title;

    @BindView(R.id.profile_edit_avatar_container)
    LinearLayout avatarContainer;
    @BindView(R.id.profile_edit_nick)
    EditText nick;

    @BindView(R.id.profile_edit_gender)
    TextView gender;
    @BindView(R.id.profile_edit_gender_container)
    LinearLayout genderContainer;
    @BindView(R.id.profile_logout)
    TextView profileLogout;
    @BindView(R.id.profile_edit_avatar)
    CircleImageView avatar;
    @BindView(R.id.profile_edit_sign)
    EditText sign;
    @BindView(R.id.profile_edit_mobile)
    TextView mobile;
    @BindView(R.id.profile_edit_weixin)
    TextView weixin;
    @BindView(R.id.profile_edit_mobile_container)
    LinearLayout mobileContainer;
    @BindView(R.id.profile_edit_weixin_container)
    LinearLayout weixinContainer;
    @BindView(R.id.profile_edit_age)
    EditText age;
    @BindView(R.id.profile_edit_area)
    TextView area;
    @BindView(R.id.profile_edit_tags)
    TextView profileEditTags;
    @BindView(R.id.profile_edit_partner_id)
    TextView partnerId;
    @BindView(R.id.profile_edit_ustatus)
    TextView ustatus;

    private ProfileEditPresenter presenter;

    private String province = "";
    private int ustatusValue = 0;

    private User user;

    private File cropTmpFile;
    private UploadConf avatarConfig;


    private boolean requestResult = false;


    public static void startForResult(Activity ctx, User user) {
        Intent intent = new Intent(ctx, ProfileEditActivity.class);
        intent.putExtra("user", user);
        intent.putExtra("requestResult", true);
        ctx.startActivityForResult(intent, AppConfig.RequestResult.REQUEST_CODE_PROFILE_EDIT);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_edit);
        ButterKnife.bind(this);
        user = (User) getIntent().getSerializableExtra("user");

        requestResult = getIntent().getBooleanExtra("requestResult", false);
        if (user == null) {
            Log.w(TAG, "need params finished...");
            finish();
            return;
        }

        presenter = new ProfileEditPresenter(this, this);


        initializeView();

        bintDefaultData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideSoftKeyboard();
    }

    @Override
    protected void onDestroy() {
        presenter.onDestory();
        super.onDestroy();

    }

    private void initializeView() {
        title.setTitle("设置");
        title.setOnTitleClickedListener(this);
        title.setTitleRightText("保存");
        title.setTitleRightVisibility(true);
        title.setTitleRightTextColor(getResources().getColor(R.color.colorPrimary));

        profileLogout.setOnClickListener(this);
        avatarContainer.setOnClickListener(this);
        genderContainer.setOnClickListener(this);
        mobileContainer.setOnClickListener(this);
        weixinContainer.setOnClickListener(this);
        partnerId.setOnClickListener(this);
        area.setOnClickListener(this);
        ustatus.setOnClickListener(this);
        profileEditTags.setOnClickListener(this);
    }

    private void bintDefaultData() {
        if (!StringUtil.isNullOrEmpty(user.avatar)) {
            ImageLoader.getInstance().loadImageView(this, user.avatar, avatar);
        }
        nick.setText(user.nickname);
        sign.setText(user.sign);

        gender.setText(user.gender.equals(User.GENDER_MALE) ? "男" : "女");

        if (StringUtil.isNullOrEmpty(user.mobile)) {
            mobile.setText("未绑定");
        } else {
            mobile.setText(user.mobile);
        }

        age.setText(user.age + "");
        province = user.province;
        area.setText(user.province);
        profileEditTags.setText(getTagDisplayLabel());

        if (StringUtil.isNullOrEmpty(user.openid)) {
            weixin.setText("未绑定");
        } else {
            if (StringUtil.isMobileNumbric(user.openid)) {
                weixin.setText("未绑定");
            } else {
                weixin.setText("已绑定");
            }
        }

        if (StringUtil.isNullOrEmpty(user.wdUserid)) {
            partnerId.setText("立即加入");
        } else {
            partnerId.setText(user.wdUserid);
        }

        ustatusValue = user.userStatus;
        String displayStr = AppUtil.getUStatusValueById(ustatusValue);
        if (StringUtil.isNullOrEmpty(displayStr)) {
             ustatus.setText("选择备孕状态");
        } else {
            ustatus.setText(displayStr);
        }
    }

    private String getTagDisplayLabel() {
        if (InitManager.getInstance().getTags() == null || InitManager.getInstance().getTags().isEmpty()) {
            return "";
        }
        if (InitManager.getInstance().getTags().size() == 1) {
            return InitManager.getInstance().getTags().get(0).name;
        } else {
            return InitManager.getInstance().getTags().get(0).name + " 等" + InitManager.getInstance().getTags().size() + "个标签";
        }
    }

    /**
     * 提交个人信息
     */
    private void updataUserInfo() {
        String newNick = nick.getText().toString().trim();
        String newSign = sign.getText().toString().trim();
        if (TextUtils.isEmpty(newNick)) {
            showToast("请输入昵称");
            return;
        }
        int newAge = 0;
        try {
            newAge = Integer.parseInt(age.getText().toString().trim());
        } catch (NumberFormatException e) {
            newAge = 0;
        }
        if (newAge <= 0) {
            showToast("您输入的年龄不合法");
            return;
        }
        String newGender = gender.getText().toString().equals("男") ? User.GENDER_MALE : User.GENDER_FEMALE;
        String newAvatar = avatarConfig == null ? user.avatar : avatarConfig.getResultFullUrl();
        showProgressDialog("正在保存...", false);
        presenter.updateUserInfo(newAvatar, newNick, newGender, newSign, newAge, province,ustatusValue);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.profile_logout:
                InitManager.getInstance().logout(this);
                break;
            case R.id.profile_edit_avatar_container:
                presenter.checkPermission(ProfileEditActivity.this);
                break;
            case R.id.profile_edit_mobile_container:
                break;
            case R.id.profile_edit_weixin_container:
                if (!StringUtil.isNullOrEmpty(user.openid) && !StringUtil.isMobileNumbric(user.openid)) {
                    return;
                }
                showProgressDialog("请稍候...", false);
                presenter.wxAuth();
                break;
            case R.id.profile_edit_gender_container:
                new BaseDialog().showSexDialog(ProfileEditActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int tag = (int) v.getTag();
                        if (tag == 1) {
                            gender.setText("男");
                        } else {
                            gender.setText("女");
                        }
                    }
                });
                break;
            case R.id.profile_edit_area:
                pickArea();
                break;
            case R.id.profile_edit_ustatus:
                pickUStatus();
                break;
            case R.id.profile_edit_tags:
                pickTags();
                break;
            case R.id.profile_edit_partner_id:
                if (StringUtil.isNullOrEmpty(user.wdUserid)) {
                    //TODO
                    WebViewActivity.start(this, HttpConfig.PARTNER_JOIN_URL, "加入合伙人", "");
                }
                break;


        }
    }

    private void pickTags() {
        TagSubscribeActivity.startForResult(this);
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RequestResult.REQUEST_CODE_PHOTOS:
                List<String> resultList = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
                Log.d(TAG, "resultList: " + (resultList == null ? "null" : "result list: " + resultList.size()));
                if (resultList != null && !resultList.isEmpty()) {
                    startCrop(resultList.get(0));
                }
                break;
            case AppConfig.RequestResult.REQUEST_CODE_CROP:
                if (cropTmpFile == null || !cropTmpFile.exists()) {
                    showToast("裁剪图片失败");
                    return;
                }
                showProgressDialog("正在上传...", false);
                presenter.compressAndUploadPhoto(cropTmpFile.getAbsolutePath());
                break;
            case AppConfig.RequestResult.REQUEST_CODE_SUBSCRIBE:
                profileEditTags.setText(getTagDisplayLabel());
                break;

        }

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onPreBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onTitleBackClicked() {
        onPreBack();
    }

    @Override
    public void onTitleRightClicked() {
        updataUserInfo();
    }

    @Override
    public void onTitleClicked() {

    }

    private void onPreBack() {
        finish();
    }

    private void startCrop(String path) {
        Log.d(TAG, "startCrop path: " + path);
        cropTmpFile = new File(AppConfig.CacheConfig.APP_IMAGE_DIR + System.currentTimeMillis() + "croped.jpg");
        if (cropTmpFile.exists()) {
            cropTmpFile.delete();

        }

        try {
            cropTmpFile.createNewFile();
        } catch (IOException e) {
            showToast("创建临时文件失败,请确保存储空间未满并且以授予医考宝典写文件的权限");
            return;
        }

        File file = new File(path);

        Uri photoURI = FileProvider.getUriForFile(ProfileEditActivity.this, getPackageName(), file);


        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(photoURI, "image/*");
        intent.putExtra("crop", "true");// 可裁剪
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropTmpFile));
        intent.putExtra("return-data", false);// 若为false则表示不返回数据
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, AppConfig.RequestResult.REQUEST_CODE_CROP);
    }


    @Override
    public void onPermissionGranted(List<String> grantPermissions) {
        PhotoPickerActivity.startForResult(this, 1, true, PhotoPickerActivity.MODE_SINGLE, new ImageConfig());
    }

    @Override
    public void onPermissionDenied(List<String> deniedPermissions) {
        showToast("您需要在设置中打开文件读取权限才能选择头像");
    }

    @Override
    public void onPictureUploadFinished(boolean success, String failReason, UploadConf config) {
        dismissProgressDialog();
        if (success) {
            avatarConfig = config;
            ImageLoader.getInstance().loadImageView(ProfileEditActivity.this, config.localPath, avatar);
        } else {
            showToast("头像上传失败 " + failReason);
        }
    }

    @Override
    public void onUpdateInfoSuccess() {
        dismissProgressDialog();
        if (requestResult) {
            setResult(RESULT_OK);
            finish();
        } else {

            finish();
        }

    }

    @Override
    public void onRequestFailed(String code, String reason) {
        dismissProgressDialog();

        showToast(reason);
    }

    @Override
    public void onAuthSuccess(AuthrizeInfo info) {
        presenter.bindWeixin(info.openId, info.accessToken, info.expireIn + "", info.unionid);
    }

    @Override
    public void onBindWeixinSuccess() {
        dismissProgressDialog();
        showToast("绑定成功");
        weixin.setText("已绑定");
    }

    private void pickArea() {
        hideSoftKeyboard();
        CityParseHelper helper = new CityParseHelper();
        helper.initData(this);
        final List<String> provinces = helper.getProvinces();
        new BaseDialog().showListDialog(this, "请选择地区", provinces, new BaseDialog.OnListItemSelectedListener() {

            @Override
            public void onListItemSelected(String value) {
                Log.d(TAG, "on province get: " + value + "|");
                province = value.trim();
                area.setText(province);
            }
        });
    }
    private void pickUStatus() {
        hideSoftKeyboard();
        new BaseDialog().showUStatusDialog(this, "选择孕育状态", new BaseDialog.OnUStatusSelectedListener() {


            @Override
            public void onUStatusSelected(UStatus status) {
                Log.d(TAG, "onUStatusSelected: " + status.value + "|");
                ustatusValue = status.id;
                ustatus.setText(status.value);
            }
        });
    }

}
